﻿using System;
using System.Collections.Generic;
using System.IO;
using Docentric.Examples.Data.BusinessObjects;
using Docentric.Examples.Data.BusinessObjects.DataModel;
using Docentric.Word;
using DTSM = Docentric.DocentricTypeSystem.Metadata;
using DTSD = Docentric.DocentricTypeSystem.Data;


namespace Docentric.Examples.Browser
{
	public class RenderingCollectionDtsExample : ExampleBase
	{
		// Constructor
		public RenderingCollectionDtsExample()
		{
			Name = "RenderingCollectionDts";
			Title = "Rendering Collection (DTS)";
			Description = "We want to create a report listing all purchase orders in a table. For this task we are using the 'List' element in combination with several 'Field' elements. The default data source on the template is a DTS List of 'Order' objects." +
                          " The DTS List object is obtained by the conversion from the 'Customer' .NET object. " +
                          "'DTS' is abbreviation of 'Docentric Type System' which represents simplified .NET type system suitable for template designing by non-technical / end users.";
		}


		// GenerateReport
		public override string GenerateReport()
		{
			// Get all orders from the database.
			IEnumerable<Order> orders = DataAccess.GetOrders();

			// Convert to the corresponding DTS list. It is assumed that a DTS schema on the template was imported from the same .NET 'Order' collection type.
			DTSD.DtsValueBase dtsOrders = DTSM.Converters.DotNetToDtsConverter.ConvertDotNetValueToDtsValue(orders);

			// Create a temporary file for the generated report document.
			string reportDocumentFileName = System.IO.Path.GetTempPath() + "GeneratedReport_" + Guid.NewGuid().ToString() + ".docx";
			using (Stream reportDocumentStream = File.Create(reportDocumentFileName))
			{
				// Open the report template file.
				using (Stream reportTemplateStream = GetReportTemplate())
				{
					// Generate the report document using 'DocumentGenerator'.
					DocumentGenerator dg = new DocumentGenerator(dtsOrders);
					DocumentGenerationResult result = dg.GenerateDocument(reportTemplateStream, reportDocumentStream);
					if (result.HasErrors)
					{
						foreach (Word.Error error in result.Errors) Console.Out.WriteLine(error.Message);
					}
				}
			}

			return reportDocumentFileName;
		}
	}
}
